# -*- coding:utf-8 -*-

from typing import List
from datetime import datetime, time
from module_admin.entity.do.role_do import SysRoleDept
from sqlalchemy import and_, delete, desc, func, or_, select, update
from sqlalchemy.ext.asyncio import AsyncSession
from module_gen.constants.gen_constants import GenConstants

from module_stock.entity.do.stock_basic_do import StockBasic
from module_stock.entity.vo.stock_basic_vo import StockBasicPageModel, StockBasicModel
from utils.page_util import PageUtil, PageResponseModel


class StockBasicDao:

    @classmethod
    async def get_by_id(cls, db: AsyncSession, stock_basic_id: int) -> StockBasic:
        """根据主键获取单条记录"""
        stock_basic = (((await db.execute(
                            select(StockBasic)
                            .where(StockBasic.id == stock_basic_id)))
                       .scalars())
                       .first())
        return stock_basic

    """
    查询
    """
    @classmethod
    async def get_stock_basic_list(cls, db: AsyncSession,
                             query_object: StockBasicPageModel,
                             data_scope_sql: str = None,
                             is_page: bool = False) -> [list | PageResponseModel]:

        query = (
            select(StockBasic)
            .where(
                StockBasic.act_ent_type == query_object.act_ent_type if query_object.act_ent_type else True,
                StockBasic.act_name == query_object.act_name if query_object.act_name else True,
                StockBasic.area == query_object.area if query_object.area else True,
                StockBasic.cnspell == query_object.cnspell if query_object.cnspell else True,
                StockBasic.curr_type == query_object.curr_type if query_object.curr_type else True,
                StockBasic.delist_date == query_object.delist_date if query_object.delist_date else True,
                StockBasic.enname == query_object.enname if query_object.enname else True,
                StockBasic.exchange == query_object.exchange if query_object.exchange else True,
                StockBasic.fullname.like(f"%{query_object.fullname}%") if query_object.fullname else True,
                StockBasic.industry.like(f"%{query_object.industry}%") if query_object.industry else True,
                StockBasic.is_hs == query_object.is_hs if query_object.is_hs else True,
                StockBasic.list_date == query_object.list_date if query_object.list_date else True,
                StockBasic.list_status == query_object.list_status if query_object.list_status else True,
                StockBasic.market == query_object.market if query_object.market else True,
                StockBasic.name.like(f"%{query_object.name}%") if query_object.name else True,
                StockBasic.symbol == query_object.symbol if query_object.symbol else True,
                StockBasic.ts_code == query_object.ts_code if query_object.ts_code else True,
                eval(data_scope_sql) if data_scope_sql else True,
            )
            # .order_by(desc(StockBasic.create_time))
            # .distinct()
        )
        stock_basic_list = await PageUtil.paginate(db, query, query_object.page_num, query_object.page_size, is_page)
        return stock_basic_list


    @classmethod
    async def add_stock_basic(cls, db: AsyncSession, add_model: StockBasicModel, auto_commit: bool = True) -> StockBasic:
        """
        增加
        """
        stock_basic =  StockBasic(**add_model.model_dump(exclude_unset=True))
        db.add(stock_basic)
        await db.flush()
        if auto_commit:
            await db.commit()
        return stock_basic

    @classmethod
    async def edit_stock_basic(cls, db: AsyncSession, edit_model: StockBasicModel, auto_commit: bool = True) -> StockBasic:
        """
        修改
        """
        edit_dict_data = edit_model.model_dump(exclude_unset=True, exclude={*GenConstants.DAO_COLUMN_NOT_EDIT})
        await db.execute(update(StockBasic), [edit_dict_data])
        await db.flush()
        if auto_commit:
            await db.commit()
        return await cls.get_by_id(db, edit_model.id)

    @classmethod
    async def del_stock_basic(cls, db: AsyncSession, stock_basic_ids: List[str], soft_del: bool = True, auto_commit: bool = True):
        """
        删除
        """
        if soft_del:
            await db.execute(update(StockBasic).where(StockBasic.id.in_(stock_basic_ids)).values(del_flag='2'))
        else:
            await db.execute(delete(StockBasic).where(StockBasic.id.in_(stock_basic_ids)))
        await db.flush()
        if auto_commit:
            await db.commit()